<template>
    <div class="app-container">
        <div class="content-top">
            <span class="content-title">知识库</span>
            <span class="add-btn" @click="handeOpen">新建知识库</span>
        </div>
        <div class="center">
            <div class="center-top">
                <span>全部空间</span>
                <div class="search">
                    <el-input placeholder="请输入内容" v-model="KEYWORDS" class="input-with-select">
                        <el-button slot="append" icon="el-icon-search" @click="getList"></el-button>
                    </el-input>
                </div>
            </div>
            <div class="center-list clearfix">
                <div class="center-item" :style="{ background: 'url(' + item.mainCover + ') center center no-repeat' }"
                    v-for="(item, index) in knowList" :key="index" @click.stop="goDetails(item)"
                    v-show="knowList.length">
                    <div class="item-title">
                        {{ item.groupName || '' }}
                    </div>
                    <div class="item-describe">
                        {{ item.intro || '' }}
                    </div>
                    <div class="tool" v-if="item.createBy == createBy">
                        <i class="el-icon-edit" @click.stop="handleEditItem(item)"></i>
                        <i class="el-icon-delete-solid" @click.stop="handleDeleteItem(item)"></i>
                    </div>
                    <div class="tool" v-else>
                        <img src="@/assets/images/know/eyes.png" alt=""
                            v-if="(!editType && item.isCanEdit == '0' && item.isCanLook == '1') || (item.isCanEdit == '1' && item.createBy != createBy)">
                        <img src="@/assets/images/know/eyes_close.png" alt=""
                            v-if="item.isCanLook == '0' && item.isCanEdit == '0'">
                    </div>
                </div>
                <div v-show="!knowList.length">没有相关数据</div>
            </div>
        </div>
        <el-dialog title="完善知识空间信息" :close-on-click-modal="false" @close="handleClose"
            :visible.sync="centerDialogVisible" width="50%" center>
            <div>
                <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px" class="demo-ruleForm">
                    <el-form-item label="名称" prop="groupName">
                        <el-input v-model="ruleForm.groupName"
                            :disabled="!editType && editId ? true : false"></el-input>
                    </el-form-item>
                    <el-form-item label="简介" prop="intro">
                        <el-input v-model="ruleForm.intro" :disabled="!editType && editId ? true : false"></el-input>
                    </el-form-item>
                    <el-form-item label="编辑方式" prop="editType">
                        <el-radio-group v-model="ruleForm.editType" :disabled="editId ? true : false">
                            <!-- <el-radio label="markdown">MarkDown</el-radio> -->
                            <el-radio label="richtext">富文本</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="权限控制类型" prop="deptorren">
                        <el-radio-group v-model="ruleForm.deptorren">
                            <el-radio label="1">部门</el-radio>
                            <el-radio label="2">人员</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="可见人员" prop="canLookRen"
                        v-if="(editType || !editId) && ruleForm.deptorren == 2">
                        <el-select v-model="ruleForm.canLookRen" placeholder="请选择" :multiple="true"
                            style="width: 100%;">
                            <el-option v-for="item in userList" :key="item.userId" :label="item.nickName"
                                :value="item.userId">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="可见部门" prop="canLookRange"
                        v-if="(editType || !editId) && ruleForm.deptorren == 1">
                        <el-cascader ref="downLoadLvlRef" @change="getCheckedNodes" collapse-tags
                            v-model="ruleForm.canLookRange" :options="deptList" :props="deptProps"
                            style="width: 100%;"></el-cascader>
                    </el-form-item>
                    <el-form-item label="可编辑人员" prop="canEditUserId" v-if="editType || !editId">
                        <el-select v-model="ruleForm.canEditUserId" placeholder="请选择" :multiple="true"
                            style="width: 100%;">
                            <el-option v-for="item in userList" :key="item.userId + ''" :label="item.nickName"
                                :value="item.userId + ''">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="创建人" prop="intro" v-if="editId">
                        {{ knowCreateBy == 'admin' ? 'admin' : getUserName() }} <span
                            style="color: #999;font-size: 12px;padding-left: 8px;">注：只有创建人可以维护知识库信息</span>
                    </el-form-item>
                    <el-form-item v-if="editId" label="修改封面" prop="intro">
                        <el-button size="small" @click="isCover = true" :disabled="!editType && editId">选择封面</el-button>
                    </el-form-item>
                </el-form>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="centerDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="handleAddKnow">确 定</el-button>
            </span>
        </el-dialog>
        <el-drawer title="我是标题" :visible.sync="isCover" size="440px" :with-header="false">
            <div class="cover clearfix">
                <div v-for="(item, i) in coverList" :key="i" class="cover-item" style="height: 180px;width: 133px;">
                    <img :src="item" alt="" @click="handleSelectImgs(item)">
                </div>
            </div>
        </el-drawer>
    </div>
</template>

<script>
import { getKnowList, deptTreeSelect, updateKnow, delKnow, addKnow, getAllUser } from "@/api/staging/know";

export default {
    name: "list",
    data() {
        return {
            editType: false, // 是否可编辑
            userList: [], // 用户列表
            knowCreateBy: '', // 知识库创建人
            deptProps: { // 部门树配置项
                label: 'deptName',
                value: 'deptId',
                multiple: true,
                emitPath: false
            },
            checkedDept: [], // 已选中的部门信息
            deptList: [], // 部门树数据
            editId: null, // 编辑ID
            ruleForm: { // 新建知识库信息
                groupName: '', // 知识库名称
                canLookRange: '', // 部门可查看范围
                intro: '', // 知识库简介
                mainCover: '', // 知识库封面
                canEditUserId: '', // 可编辑人员
                deptorren: '1', // 1：部门 2：人员
                editType: 'richtext', // 编辑类型
                canLookRen: '' // 可查看人员
            },
            rules: {  // 表单验证
                groupName: [
                    { required: true, message: '请输入知识库名称', trigger: 'blur' }
                ],
                canLookRange: [
                    { required: true, message: '请选择可见范围', trigger: 'change' }
                ],
                editType: [
                    { required: true, message: '请选择编辑方式', trigger: 'change' }
                ],
                deptorren: [
                    { required: true, message: '请选择权限控制类型', trigger: 'change' }
                ],
                canLookRen: [
                    { required: true, message: '请选择', trigger: 'change' }
                ]
            },
            knowList: [], // 知识库列表
            centerDialogVisible: false, // 新建弹框展示
            KEYWORDS: '',  // 搜索关键词
            coverList: [ // 封面列表
                require("@/assets/images/know/know-bg-02.png"), require("@/assets/images/know/know-bg-05.png"), require("@/assets/images/know/know-bg-01.png"),
                require("@/assets/images/know/know-bg-03.png"), require("@/assets/images/know/know-bg-06.png"), require("@/assets/images/know/know-bg-08.png"),
                require("@/assets/images/know/know-bg-04.png"), require("@/assets/images/know/know-bg-07.png"), require("@/assets/images/know/know-bg-09.png")
            ],
            isCover: false, // 封面列表展示
            loading: false,	//加载状态
        };
    },
    computed: {
        getUserName() {
            return function () {
                return (
                    this.userList && this.userList.length && this.userList.filter(it => it.userName == this.knowCreateBy)[0]?.nickName
                )
            }
        },
        createBy() {
            return this.$store.state.user.name
        },
    },
    created() {
        this.getDeptList()
        this.getList()
        this.getUserList()
    },
    methods: {
        getCheckedNodes() {
            this.checkedDept = []
            let downLoadLvl = this.$refs.downLoadLvlRef.getCheckedNodes()
            downLoadLvl.forEach(item => {
                this.checkedDept.push(item.value)
            })
        },
        // 获取人员列表
        getUserList() {
            getAllUser().then(response => {
                this.userList = response.data;
            });
        },
        /** 查询部门列表 */
        getDeptList() {
            deptTreeSelect().then(response => {
                this.loading = false;
                if (response.code == 200) {
                    this.deptList = this.handleTree(response.data, "deptId");
                } else {
                    this.$modal.msgError("操作失败！");
                }
            });
        },
        // 切换封面
        handleSelectImgs(item) {
            updateKnow({ mainCover: item, id: this.editId }).then(response => {
                this.loading = false;
                if (response.code == 200) {
                    this.getList();
                    this.$modal.msgSuccess("修改成功");
                } else {
                    this.$modal.msgError("操作失败！");
                }
            });
            this.centerDialogVisible = false;
            this.isCover = false;
        },
        // 删除知识库
        handleDeleteItem(val) {
            if (this.createBy !== val.createBy) {
                swal("无操作权限！", "warning");
                return false
            }
            this.$modal.confirm('确定要删除吗？').then(() => {
                this.loading = true;
                return delKnow({ id: val.id });
            }).then(() => {
                this.loading = false;
                this.getList();
                this.$modal.msgSuccess("删除成功");
            }).finally(() => {
                this.loading = false;
            });
        },
        // 关闭新增弹框
        handleClose() {
            this.centerDialogVisible = false;
            this.ruleForm = {
                groupName: '',
                canLookRange: '',
                intro: '',
                mainCover: '',
                canEditUserId: '',
                editType: 'richtext',
                canLookRen: '',
                deptorren: '1'
            }
            this.$refs.ruleForm.resetFields();
        },
        //知识库详情
        goDetails(val) {
            if (val.isCanLook == '0') {
                this.knowCreateBy = val.createBy
                this.$modal.msgError(`无操作权限！如需查看请联系创建者[${this.getUserName() || 'admin'}]添加权限`);
                return false;
            }
            let editFlag;
            if (val.isCanEdit == '1') {
                editFlag = 'edit';
            } else if (val.isCanEdit == '0' && val.isCanLook == '1') {
                editFlag = 'read';
            }
            let params = { FID: val.id, editFlag };
            this.$router.push({ path: '/staging/knowDetails', query: params });
        },
        // 知识库创建保存
        handleAddKnow() {
            this.$refs.ruleForm.validate((valid) => {
                if (valid) {
                    let url = this.editId ? updateKnow : addKnow
                    this.ruleForm.canLookRange = this.checkedDept.length ? this.checkedDept.join() : ''
                    this.ruleForm.canLookRen = this.ruleForm.canLookRen.length ? this.ruleForm.canLookRen.join() : ''
                    this.ruleForm.canEditUserId = this.ruleForm.canEditUserId.length ? this.ruleForm.canEditUserId.join() : ''
                    if (this.ruleForm.deptorren == 1) {
                        this.ruleForm.canLookRen = ''
                    } else {
                        this.ruleForm.canLookRange = ''
                    }
                    let data = this.editId ? { id: this.editId, tm: new Date().getTime(), ...this.ruleForm } : { state: 2, tm: new Date().getTime(), ...this.ruleForm }
                    url(data).then(response => {
                        this.loading = false;
                        if (response.code == 200) {
                            if (!this.editId) {
                                this.handleDataAdd(response.data)
                            }
                            this.centerDialogVisible = false;
                            this.ruleForm = {
                                groupName: '',
                                canLookRange: '',
                                intro: '',
                                mainCover: '',
                                canEditUserId: '',
                                editType: 'richtext',
                                deptorren: '1',
                                canLookRen: ''
                            }
                            this.getList()
                            this.$modal.msgSuccess("操作成功！", "success");
                        } else {
                            this.$modal.msgError("操作失败！");
                        }
                    });
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        handleDataAdd(id) {
            let params = {
                parentId: id, groupName: '', content: ''
            }
            addKnow(params).then(response => {
                if (response.code != 200) {
                    this.$modal.msgError("操作失败！");
                }
            });
        },
        handeOpen() {
            this.editId = null
            this.centerDialogVisible = true
        },
        handleEditItem(val) {
            this.ruleForm.groupName = val.groupName
            this.ruleForm.intro = val.intro
            this.ruleForm.canLookRange = val.canLookRange ? val.canLookRange.split(",") : ''
            this.ruleForm.canEditUserId = val.canEditUserId ? val.canEditUserId.split(",") : ''
            this.ruleForm.canLookRen = val.canLookRen ? val.canLookRen.split(",") : ''
            this.checkedDept = val.canLookRange && val.canLookRange.length ? val.canLookRange.split(",") : ''
            this.ruleForm.deptorren = val.deptorren
            this.ruleForm.editType = val.editType
            this.knowCreateBy = val.createBy;
            this.editId = val.id;
            this.editType = this.createBy == val.createBy ? true : false
            this.centerDialogVisible = true;
        },
        //获取列表
        getList() {
            this.loading = true;
            getKnowList({ groupName: this.KEYWORDS, parentId: 0 }).then(response => {
                this.loading = false;
                if (response.code == 200) {
                    if (response.rows.length) {
                        this.knowList = response.rows.map(item => ({
                            ...item,
                            mainCover: item.mainCover ? item.mainCover : require('@/assets/images/know/know-bg-01.png')
                        }))
                    } else {
                        this.knowList = []
                    }
                } else {
                    this.$modal.msgError("操作失败！");
                }
            });
        },
    }
};
</script>
<style lang="scss" scoped>
.content-top {
    padding: 8px 20px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-bottom: 1px solid #d1d0d0;

    .content-title {
        font-size: 16px;
        color: #333;
        font-weight: 700;
    }

    .add-btn {
        cursor: pointer;
        width: 120px;
        height: 35px;
        display: flex;
        justify-content: center;
        align-items: center;
        border-radius: 10px;
        color: rgb(20, 86, 246);
        border: 1px solid rgb(20, 86, 246);
    }
}

.center {
    .center-top {
        display: flex;
        padding: 50px 20px 26px 20px;
        align-items: center;
        justify-content: space-between;

        span {
            font-size: 16px;
            color: #333;
        }

        .search {
            display: flex;
            align-items: center;

            .form-control {
                background-color: #fff;
            }

            a {
                margin-left: 6px;
            }
        }
    }

    .center-list {
        padding: 0 20px 20px;

        .center-item {
            position: relative;
            cursor: pointer;
            height: 224px;
            width: 160px;
            padding: 36px 26px 0 20px;
            border-radius: 10px;
            margin: 0 20px 20px 0;
            box-sizing: border-box;
            float: left;
            color: #fff;
            // border: 1px solid #000;
            box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.3);
            // background: url(../../images/know/bg.png) center center no-repeat;
            background-size: 100% 100% !important;

            .item-title {
                font-size: 17px;
                color: #fff;
                margin-bottom: 12px;
                overflow: hidden;
                text-overflow: ellipsis;
                -webkit-line-clamp: 2;
                display: -webkit-box;
                word-break: break-all;
                -webkit-box-orient: vertical;
            }

            .item-describe {
                font-size: 14px;
                line-height: 26px;
                overflow: hidden;
                text-overflow: ellipsis;
                -webkit-line-clamp: 3;
                display: -webkit-box;
                word-break: break-all;
                -webkit-box-orient: vertical;
            }

            .tool {
                position: absolute;
                padding: 0 10px;
                margin-left: -50%;
                bottom: 10px;
                left: 50%;
                width: 100%;
                height: 35px;
                display: flex;
                align-items: center;
                justify-content: space-between;

                img {
                    width: 24px;
                }

                i {
                    font-size: 17px;
                }
            }
        }

        .center-item:hover {
            box-shadow: inset 0 -4px 18px rgba(0, 0, 0, 0.6);
            /* 添加底部内阴影效果 */
        }
    }
}

.cover {
    padding: 0;

    .cover-item {
        width: 30%;
        height: 65px;
        margin: 5px;
        float: left;

        img {
            width: 100%;
            height: 100%;
            cursor: pointer;
        }
    }
}
</style>